package com.zyf.heixiang.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zyf.heixiang.common.BaseContext;
import com.zyf.heixiang.common.R;
import com.zyf.heixiang.entity.AddressBook;
import com.zyf.heixiang.mapper.AddressBookMapper;
import com.zyf.heixiang.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 地址簿管理
 */
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
@Autowired
private AddressBookMapper addressBookMapper;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 获取当前用户所有地址
     * @return
     */
    @Cacheable(value = "addressBookCache",
            key = "'addressBookList_' + #session.getAttribute('user')",
            unless = "#result.getCode() == 0 ")
    @GetMapping("/list")
    public R<List<AddressBook>> getList(HttpSession session) {
        //1.从线程池中取出当前用户id，当然也可以用session来取
        Long userId = BaseContext.getCurrentId();
        log.info("userId={}", userId);

        //2.根据用户id去查询 当前用户的所有地址簿
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(userId);

        //3.用mp编写对应的sql：select * from address_book where user_id = #{userId}
        LambdaQueryWrapper<AddressBook> qw = new LambdaQueryWrapper<>();
        qw.eq(userId != null, AddressBook::getUserId, userId);
        qw.orderByDesc(AddressBook::getIsDefault);
        qw.orderByDesc(AddressBook::getUpdateTime);
        //4.查询即可
        List<AddressBook> list = addressBookService.list(qw);

        return list != null ? R.success(list) : R.error("获取地址簿失败");
    }


    /**
     * 查询默认地址
     */
    @Cacheable(value = "addressBookCache",
            key = "'addressBookDefault_' + #session.getAttribute('user')",
            unless = "#result.getCode() == 0 ")
    @GetMapping("/default")
    public R<AddressBook> getDefault(HttpSession session) {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        queryWrapper.eq(AddressBook::getIsDefault, 1);

        //SQL:select * from address_book where user_id = ? and is_default = 1
        AddressBook addressBook = addressBookService.getOne(queryWrapper);

        if (null == addressBook) {
            return R.error("没有找到该对象");
        } else {
            return R.success(addressBook);
        }
    }

    /**
     * 设置默认地址
     * 默认 0 否 1是
     * 删除addressBookDefault缓存
     */
    @PutMapping("/default")
    @Transactional
    @CacheEvict(value = "addressBookCache", allEntries = true)
    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook,HttpSession session) {

        log.info("id={}", addressBook.getUserId());
        //1.获取当前用户id
        Long userId = BaseContext.getCurrentId();

        //2.根据用户id，查询地址，把地址状态全部设置为 0
        LambdaUpdateWrapper<AddressBook> qw = new LambdaUpdateWrapper<>();
        qw.eq(userId != null, AddressBook::getUserId, userId);
        qw.set(AddressBook::getIsDefault, 0);
        addressBookService.update(qw);

        //3.将当前地址的设置的状态设置为1，并保存
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);

        return R.success(addressBook);
    }

    /**
     * 根据id，查询单条地址记录，用于回显
     * @param id
     * @return
     */
    @Cacheable(value = "addressBookCache",
            key = "'addressBook_'+#id",
            unless = "#result.getCode() == 0")
    @GetMapping("/{id}")
    public R<AddressBook> getById(@PathVariable Long id) {
        log.info("id={}", id);
        AddressBook addressBook = addressBookService.getById(id);
        log.info(addressBook.toString());
        return addressBook != null ? R.success(addressBook) : R.error("没有该记录");
    }

    /**
     * 新增地址
     *
     * @param addressBook
     * @return
     */
    @CacheEvict(value = "addressBookCache", allEntries = true)
    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();
        log.info("userid={}", userId);
        addressBook.setUserId(userId);
        boolean flag = addressBookService.save(addressBook);
        return flag ? R.success("新增成功") : R.error("新增失败");
    }

    /**
     * 删除地址
     * @param id id
     * @return
     */
    @CacheEvict(value = "addressBookCache", allEntries = true)
    @DeleteMapping
    public R<String> delete(@RequestParam("ids") Long id) {
        log.info("id={}", id);
        boolean flag = addressBookService.removeById(id);
        return flag ? R.success("删除成功") : R.error("删除失败");
    }

    /**
     * 修改地址
     * @param addressBook
     * @return
     */
    @PutMapping
    @CacheEvict(value = "addressBookCache", allEntries = true)
    public R<String> update(@RequestBody AddressBook addressBook) {
        boolean flag = addressBookService.updateById(addressBook);
        return flag ? R.success("保存成功") : R.error("保存失败");
    }

}
